﻿using MediatR;
using MyRabbit.Application.Command.ImmuneCommand;
using MyRabbit.Application.ErrorCode;
using MyRabbit.Domain;
using MyRabbit.Repositories;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace MyRabbit.Application.CommandHandler.ImmuneCommandHandler
{
    public class AddImmuneCommandHandler : IRequestHandler<AddImmuneCommand, APIResult<object>>
    {
        private readonly IRepository<Immune> ImmunRep;
        private readonly IRepository<BreedImmune> BreedImmuneRep;
        public AddImmuneCommandHandler(IRepository<Immune> immunRep, IRepository<BreedImmune> breedImmuneRep)
        {
            ImmunRep = immunRep;
            BreedImmuneRep = breedImmuneRep;
        }

        public async Task<APIResult<object>> Handle(AddImmuneCommand request, CancellationToken cancellationToken)
        {
            APIResult<object> result = new APIResult<object>();
            result.Code=Codes.添加成功;
            result.Message = Codes.添加成功.ToString();

            using(TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    Immune immune=new Immune();
                    immune.FeedingDays =request.FeedingDays;
                    immune.ImmunityType=request.ImmunityType;
                    immune.ImmunityMethod=request.ImmunityMethod;
                    immune.Creator=request.Creator;
                    immune.CreateTime=DateTime.Now;
                    await ImmunRep.InsertAsync(immune);


                    BreedImmune breedImmune = new BreedImmune();
                    breedImmune.BreedId=request.BreedId;
                    breedImmune.ImmuneId=immune.ImmuneId;

                    await BreedImmuneRep.InsertAsync(breedImmune);
                    result.Data = "添加养殖免疫成功";


                    //提交事务
                    scope.Complete();
                }
                catch (Exception exp)
                {

                    result.Code = Codes.添加失败;
                    result.Message = Codes.添加失败.ToString()+exp.Message;
                }
            }

            return await Task.FromResult(result);
        }
    }
}
